﻿#pragma once

#ifndef ATS2837_BLEDEVICE_H
#define ATS2837_BLEDEVICE_H

#include <QObject>
#include <QTimer>
#include <QBluetoothDeviceDiscoveryAgent>
#include <QBluetoothDeviceInfo>
#include <qbluetoothuuid.h>
#include <qbluetoothserviceinfo.h>

#include <qlowenergycontroller.h>
#include <qlowenergyservice.h>
#include <qlowenergydescriptor.h>

#include "comm_impl.h"

#define USE_CFDL 1

enum
{
    BLESearchStart = 0,
    BLESearchStop,
    BLEFindDevInvalid,
    BLEConnect,
    BLEDisconnect,
    BLETransFailed,
    BLETransEnd,
};

class DevPtlModel;
class BleDevice : public QObject
{
    Q_OBJECT
public:
    explicit BleDevice(QObject *parent = nullptr);
    ~BleDevice();

    static BleDevice* Instance();

    void bleSearchStart();
    void bleSearchStop();

    void bleDisconnet();
    void bleConnect(const QString &);
    void sendData(const QByteArray &);

    void sendData_buf(const char*, uint16_t);

    void BLETxNotify(bool);

    bool isBleConnect();
    bool isBleSearch();

    void updateFirmware(const QByteArray& rawBin, quint16 segment, const QString& suffix);

signals:
    void bleSignalLog(UsrCommImpl::logType, const QString&, const QString&);
    void bleStatus(quint16);
    void signalBleInfo(const QString&, const QString&);
    void signalBleUUID(const QString&);

    void SignalUpdateProgress(int);

private slots:
    void SlotTimer();
    void slotDevDiscovered(const QBluetoothDeviceInfo& info);

    void slotRecorderDiscovered(QBluetoothUuid);

    void slotRecorderStateChanged(QLowEnergyService::ServiceState);

    void slotRecorderCharacteristicChanged(const QLowEnergyCharacteristic&, const QByteArray&);

    void slotRecorderCharacteristicRead(const QLowEnergyCharacteristic&, const QByteArray&);

    void slotRecorderCharacteristicWrite(const QLowEnergyCharacteristic&, const QByteArray&);

    void slotBleError(QLowEnergyService::ServiceError error);

private:
    void recorderSearched(QBluetoothDeviceInfo&);
    void recorderSearchService();

private:
    QBluetoothDeviceDiscoveryAgent* mDevDiscoveryAgent;
    QLowEnergyController* mBleCtrl;
    QLowEnergyService* mBleService;

    bool bleSearchFlag = false;
    bool bleConnFlag = false;

    bool bTxNotify   = false;
    bool bCtrlNotify = false;

    bool bRxWrite = false;

    QLowEnergyCharacteristic m_ChRxWrite;
    QLowEnergyCharacteristic m_ChTxNotify;
    QLowEnergyCharacteristic m_ChCtrlNotifyWrite;

    QLowEnergyDescriptor notify_descriptor;
    QLowEnergyDescriptor tx_descriptor;
    QLowEnergyDescriptor rx_descriptor;

    QBluetoothUuid dev_uuid;

    QTimer *timer;

    DevPtlModel*  _ptl;

    uint8_t _ptlPort = 0;

    quint16 slice_size = 0;
    quint32 slice_num = 0;
    quint32 slice_index = 0;

    bool m_IsTrans = false;
};

#endif

